package com.blb.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO模型的服务器
 */
public class BIOServer {

    public static final int PORT = 7777;

    public void start(){
        //创建服务器端Socket
        try(ServerSocket serverSocket = new ServerSocket(PORT)){
            //循环获得客户端
            while(true){
                Socket accept = serverSocket.accept();
                //启动线程读取客户端消息
                new Thread(() -> {
                    try {
                        ObjectInputStream in = new ObjectInputStream(accept.getInputStream());
                        ObjectOutputStream out = new ObjectOutputStream(accept.getOutputStream());
                        String msg = in.readUTF();
                        System.out.println("客户端" + accept.getInetAddress() + "说：" + msg);
                        //发消息给客户端
                        out.writeUTF("Hello，客户端我是服务器！！！");
                        out.flush();
                        in.close();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new BIOServer().start();
    }
}
